package com.usian.controller;

import com.usian.feign.ItemServiceFeign;
import com.usian.feign.SSOFeign;
import com.usian.pojo.TbItem;
import com.usian.pojo.TbUser;
import com.usian.utils.CookieUtils;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户注册与登录
 */
@RestController
@RequestMapping("/frontend/sso")
public class SsoController {
    @Autowired
    private SSOFeign ssoFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Autowired
    private ItemServiceFeign itemServiceFeign;

    /**
     * 校验用户注册信息
     * @param checkValue
     * @param checkFlag
     * @return
     */
    @RequestMapping("checkUserInfo/{checkValue}/{checkFlag}")
    public Result checkUserInfo(@PathVariable String checkValue,
                                @PathVariable Integer checkFlag){
        Boolean checkUserInfo= ssoFeign.checkUserInfo(checkValue,checkFlag);
        if(checkUserInfo){
            return Result.ok(checkUserInfo);
        }
        return Result.error("校验失败");
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @RequestMapping("/userRegister")
    public Result userRegister( TbUser user){
        Integer userRegister = ssoFeign.userRegister(user);
        if(userRegister==1){
            return Result.ok();
        }
        return Result.error("注册失败");
    }

    /**
     * 用户登陆
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/userLogin")
    public Result userLogin(HttpServletRequest request,String username,String password) {

        Map map = ssoFeign.userLogin(username, password);
        //1.从cookie中查询商品列表
        Map<String, TbItem> map1=getCartFromCookie(request);

        /*//2、将商品添加大购物车中
        addItemToCart(map1,itemId,num);
        //3、将购物车缓存到 redis 中
        Boolean addCartToRedis = this.addCartToRedis(userId, cart);*/
        if (map != null) {
            return Result.ok(map);
        }
        return Result.error("登录失败");
    }

    /**
     * 将商品添加到购物车中
     * @param map
     * @param itemId
     * @param num
     */
    private void addItemToCart(Map<String, TbItem> map, Long itemId, Integer num) {
        //先从购物车中取商品
        TbItem tbItem = map.get(itemId.toString());
        //判断是否存在
        if (tbItem != null){
            //若存在 数量商品相加
            tbItem.setNum(tbItem.getNum()+num);
        }else{
            //若不存在  根据id查询商品 并将其添加到购物车
            tbItem = itemServiceFeign.selectItemInfo(itemId);
            tbItem.setNum(num);
        }
        map.put(itemId.toString(),tbItem);
    }
    /**
     * 获取购物车
     * @param request
     * @return
     */
    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request) {
        String cookieValue = CookieUtils.getCookieValue(request, this.CART_COOKIE_KEY, true);
        if (StringUtils.isNotBlank(cookieValue)){
            //购物车已存在
            Map map = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return map;
        }
        //购物车不存在
        return new HashMap<String, TbItem>();
    }

    /**
     * 查询用户登录是否过期
     * @param token
     * @return
     */
    @RequestMapping("/getUserByToken/{token}")
    public Result getUserByToken(@PathVariable String token) {
        TbUser tbUser = ssoFeign.getUserByToken(token);
        if(tbUser!=null){
            return Result.ok();
        }
        return Result.error("登录过期");
    }

    /**
     * 用户退出登录
     */
    @RequestMapping("/logOut")
    public Result logOut(String token){
        Boolean logOut = ssoFeign.logOut(token);
        if(logOut){
            return Result.ok();
        }
        return Result.error("退出失败");
    }
}
